<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>友链管理</span>
            </div>
        </template>
        <div style="width: 100%;">
            <el-form :inline="true" :model="form" class="demo-form-inline">
                <el-form-item label="用户名字">
                    <el-input v-model="form.name" placeholder="输入用户名" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">
                        <el-icon class="el-input__icon mr-2">
                            <search />
                        </el-icon>
                        查询
                    </el-button>
                </el-form-item>
            </el-form>
            <div class=""><el-button type="danger" size="small" :icon="Delete" @click="handleClick($event)">全部删除</el-button>
            </div>
            <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane name="allLink" label="用户">
                    <el-table size="small" ref="multipleTableRef" :data="tableData" style="width: 100%" max-height="380"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" />
                        <el-table-column type="index" width="75" label="序号" />
                        <el-table-column label="网站头像" width="120">
                            <template #default="scope">
                                <el-avatar :src="scope.row.avatar" />
                            </template>
                        </el-table-column>
                        <el-table-column property="name" label="账号" width="150" />
                        <el-table-column label="权限" width="180">
                            <template #default="scope">
                                <el-select v-model="scope.row.role" class="m-2" placeholder="Select" size='default'
                                    style="width: 80%">
                                    <el-option v-for="item in options" :key="item.role" :label="item.value"
                                        :value="item.role" @click="changeRole(scope.row.id, item.role)" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column property="address" label="地址" width="150" />
                        <el-table-column property="applyTime" label="创建日期" width="120" />
                        <el-table-column property="accessTime" label="修改日期" width="120" />
                        <el-table-column fixed="right" label="选项" width="120">
                            <template #default="scope">
                                <el-popover :visible="scope.row.visible" placement="top" :width="160">
                                    <div class="mt-2">
                                        <p>确定要删除吗?</p>
                                        <el-button size="small" type="primary"
                                            @click="scope.row.visible = false">取消</el-button>
                                        <el-button size="small" type="danger"
                                            @click="handledelete($event, 'single', scope.row)">确定</el-button>
                                    </div>
                                    <template #reference>
                                        <el-button link type="danger" size="small"
                                            @click="getcurrentvisible(scope.row)">删除</el-button>
                                    </template>
                                </el-popover>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </div>
        <pagination :currentPage="allcurrentPage" :pageSize="allpageSize" :total="alltotal" @updatepage="Allchangepage">
        </pagination>
    </el-card>
</template>

<script setup>
import moment from 'moment';
import { onMounted, reactive, ref, inject, watch } from 'vue'
import dialogg from '@/components/dialog.vue';
import pagination from '@/components/pagination.vue';
import {
    Search,
    Delete
} from '@element-plus/icons-vue'
import { deleteimg } from "@/api/friend.js"
let reload = inject('reload')
import { getallusers, getusernum, deleteusers, deleteuserscorver,tochangerole } from "@/api/users.js"
let deletelist = ref([])
let activeName = ref('allLink')
let iszhefirstSerch = ref(true)
let tableData = ref([
    {
        id: 1,
        avatar: "",
        name: "谢小康",
        address: "成都",
        applyTime: "2021-02-03",
        accessTime: "2021-02-03",
        role: 1,
        visible: false
    }
])
let form = ref({
    name: ""
})
let options = ref([
    {
        role: 1,
        value: "超级管理员"
    },
    {
        role: 2,
        value: "管理员"
    },
    {
        role: 3,
        value: "普通用户"
    }
])
let allcurrentPage = ref(1)
let allpageSize = ref(8)
let alltotal = ref()
let tempcurrentpage = ref()
onMounted(async () => {
    let count = await getusernum()
    alltotal.value = count.data.data
    await getuserss()
})
function handleClick() {
    ElMessageBox.confirm(
        '确定要删除',
        'Warning',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    ).then(async () => {
        let corverlist = []
        let deleteidlist = deletelist.value.map(item => {
            corverlist.push(item.avatar.split("/").pop())
            return item.id
        })
        let res = await deleteusers({ deleteidlist })
        if (res.data.status == 200) {
            deletelist.value = []
            let res2 = await deleteuserscorver({ corverlist })
            if (res2.data.status == 200) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            }
            reload()
        } else {
            deletelist.value = []
            ElMessage({
                type: 'error',
                message: '删除失败',
            })
            reload()
            return
        }

    })
}

async function getuserss(keyword = "") {
    let data = {
        page: allcurrentPage.value,
        pageSize: allpageSize.value
    }
    if (keyword != "") {
        data["keyword"] = keyword
    }
    let users = await getallusers(data)
    if (users.data.status == 200) {
        if (users.data.data.count) {
            alltotal.value = users.data.data.count
        }
        tableData.value = users.data.data.data.map(item => {
            return {
                id: item.id,
                avatar: item.Users_corver,
                name: item.Users_name,
                address: item.Users_address,
                role: item.Users_role,
                applyTime: moment(item.createdAt).format('YYYY-MM-DD'),
                accessTime: moment(item.updatedAt).format('YYYY-MM-DD'),
                visible: false
            }
        })
    } else {
        if (!users.data.data.data) {
            tableData.value = []
            alltotal.value = 0
            ElMessage({
                showClose: true,
                message: '暂无数据',
                type: 'error',
            })
        }
    }
}
/* 修改页码 */
async function Allchangepage(val) {
    allcurrentPage.value = val
    if (iszhefirstSerch.value) {
        await getuserss()
    } else {
        await getuserss(form.value.name)
    }
}
const handleSelectionChange = (val) => {
    deletelist.value = val
}
/* 查询用户 */
const onSubmit = async () => {
    if (form.value.name == "") {
        ElMessage({
            showClose: true,
            message: '请填写用户名',
            type: 'error',
        })
    } else {
        allcurrentPage.value = 1
        if (iszhefirstSerch.value) {
            tempcurrentpage.value = allcurrentPage.value
            await getuserss(form.value.name)
        } else {
            await getuserss(form.value.name)
        }
    }
}
const handledelete = async (e, flge, data) => {
    if (flge == 'single') {
        deletelist.value = [data]
        let cover = data.avatar
        let deleteidlist = deletelist.value.map(item => {
            return item.id
        })
        let res = await deleteusers({ deleteidlist })
        if (res.data.status == 200) {
            let result = await deleteimg({
                oldimg: cover.split("/").pop(),
            })
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            reload()
            deletelist.value = []
        } else {
            deletelist.value = []
            ElMessage({
                type: 'error',
                message: '删除失败',
            })
            reload()
        }

    }
}
function getcurrentvisible(val) {
    tableData.value.forEach((item) => {
        if (item.id == val.id) {
            item.visible = true
        }
    })
}
async function changeRole(userid, role) {
    console.log(userid, role);
    let res = await tochangerole({ userid, role })
    console.log(res);
    if (res.data.status == 200) {
        ElMessage({
            type: 'success',
            message: '修改成功',
        })
        reload()
    } else {

    }
}
watch(() => form.value.name, async (newval, oldval) => {
    if (newval == '') {
        iszhefirstSerch.value = true
        allcurrentPage.value = tempcurrentpage.value
        let count = await getusernum()
        alltotal.value = count.data.data
        await getuserss()
    }
    if (newval !== '' && oldval.length > newval.length) {
        iszhefirstSerch.value = false
        allcurrentPage.value = 1
        await getuserss(form.value.name)
    }
})
</script>

<style lang="css" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

:deep(.el-card__header) {
    padding: 5px 25px !important;
}
</style>